import Vue from "vue";
import VueRouter from "vue-router";
// 添加login的路由，
import Login from "../components/login";
// 添加home的路由
import Home from "../components/home";
// 添加welcome的路由
import Welcome from "../components/welcome";
import Users from "../components/user/users";
Vue.use(VueRouter);

const routes = [
  // 因为我们是想要在进入到APP主页，就直接跳转到login，
  // 所以我们需要进重定向
  {
    path: "/",
    redirect: "/login",
  },
  {
    path: "/login",
    component: Login,
  },
  {
    path: "/home",
    component: Home,
    redirect: "/welcome",
    children: [
      {
        path: "/welcome",
        component: Welcome,
      },
      {
        path: "/users",
        component: Users,
      },
    ],
  },
];

const router = new VueRouter({
  routes,
});

// 挂在路由导航守卫
router.beforeEach((to, from, next) => {
  // to是想要去哪里， from是从哪里来，next是下一步的操作函数
  if (to.path === "/login") return next();
  const tonkenStr = window.sessionStorage.getItem("token");
  if (!tonkenStr) {
    return next("/login");
  } else {
    next();
  }
});

export default router;
